package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.Loginvo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
        @Autowired
        private ApUserService apUserService;

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        String hashpw = BCrypt.hashpw(dto.getPassword(), BCrypt.gensalt());
        LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApUser::getPhone,dto.getPhone());
        List<ApUser> list = apUserService.list(lambdaQueryWrapper);
        for (ApUser apUser : list) {
            String password = apUser.getPassword();
            if (BCrypt.checkpw(dto.getPassword(), password)){
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                Loginvo loginvo=new Loginvo();
                loginvo.setUser(apUser);
                loginvo.setToken(token);
                return ResponseResult.okResult(loginvo);
            }
        }
        return ResponseResult.errorResult(404,"用户名或密码错误");
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
